//
//  LZAddTagViewController.m
//  LZHundredJie
//
//  Created by apple on 16/5/7.
//  Copyright © 2016年 m14a.cn. All rights reserved.
//

#import "LZAddTagViewController.h"
#import "LZTagButton.h"
#import "LZTagTextField.h"
#import "SVProgressHUD.h"

@interface LZAddTagViewController () <UITextFieldDelegate>

/** 用来容纳所有按钮和文本框*/
@property (nonatomic, weak) UIView *contentView;
/** 文本框*/
@property (nonatomic, weak) LZTagTextField *textField;
/** 提醒按钮 */
@property (nonatomic, weak) UIButton *tipButton;
/** 存放所有的标签按钮*/
@property (nonatomic, strong) NSMutableArray *tagButtons;
@end

@implementation LZAddTagViewController


#pragma mark - 懒加载

- (NSMutableArray *)tagButtons{

    if (_tagButtons == nil) {
        _tagButtons = [NSMutableArray array];
    }
    return _tagButtons;
}

- (UIButton *)tipButton{

    if (_tipButton == nil) {
        // 1.创建提醒按钮
        UIButton *tipButton = [[UIButton alloc] init];
        [tipButton addTarget:self action:@selector(tipClick) forControlEvents:UIControlEventTouchUpInside];
        tipButton.width = self.contentView.width;
        tipButton.height = LZTagH;
        tipButton.x = 0;
        tipButton.backgroundColor = LZColor(59, 117, 198);
        tipButton.titleLabel.font = [UIFont systemFontOfSize:14];
        
        tipButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        tipButton.contentEdgeInsets = UIEdgeInsetsMake(0, LZCommonSmallMargin, 0, 0);
        [self.contentView addSubview:tipButton];
        _tipButton = tipButton;
    }
    return _tipButton;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNav];
    [self setupContentView];
    [self setupTextField];
    [self setupTags];
}

- (void)setupTags
{
//    self.textField.text = @"哈哈";
//    [self tipClick];
//    self.textField.text = @"呵呵";
//    [self tipClick];
    
    for (NSString *tag in self.tags) {
        self.textField.text = tag;
        [self tipClick];
    }
}

- (void)setupNav{
    self.title = @"添加标签";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStyleDone) target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:(UIBarButtonItemStyleDone) target:self action:@selector(done)];
}

- (void)setupContentView {

    UIView *contentView = [[UIView alloc] init];
    contentView.x = LZCommonSmallMargin;
    contentView.y = LZNavBarMaxY + LZCommonSmallMargin;
    contentView.width = self.view.width - 2 * contentView.x;
    contentView.height = self.view.height;
    contentView.frame = CGRectMake(contentView.x, contentView.y, contentView.width, contentView.height);
    [self.view addSubview:contentView];
    self.contentView = contentView;
}

- (void)setupTextField {

    LZTagTextField *textField = [[LZTagTextField alloc] init];
    textField.delegate = self;
    [textField addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];
    textField.width = self.contentView.width;
    textField.height = LZTagH;
    textField.placeholder = @"多个标签用逗号或者换行隔开";
    textField.placeholderColor = [UIColor grayColor];
 
    // 弹出键盘
    [textField becomeFirstResponder];
    [self.contentView addSubview:textField];
    self.textField =  textField;
    // 下面这句代码如果写在addSubview前面可能不好使，不好使就写在后面原因是下面的
    // 刷新的前提:这个控件已经添加到父控件
    // 这句代码含义是:如果光标没有出现,就写这句代码强制刷新一下
    // 如果出现了，就可以不写这句话
    // 以后凡是一些东西应该正常出来，或者显示正常效果,但是效果不对
    // 就可以尝试使用layoutIfNeeded
    [textField layoutIfNeeded];
    
    // 含义,弱引用,防止循环引用
    __weak typeof(self) weakSelf = self;
    textField.deleteBackardOperation = ^{
        
        // 判断文本框是否有文字
        if (weakSelf.textField.hasText || weakSelf.tagButtons.count == 0) return ;
        
        // 点击了最后一个标签按钮(删掉最后一个标签按钮)
        [weakSelf tagClick:self.tagButtons.lastObject];
    };
}


#pragma mark - 监听

/**
 *  监听textField文字改变
 */
- (void)textDidChange{
    
    if (self.textField.hasText) {
        
        NSString *text = self.textField.text;
        NSString *lastChar = [text substringFromIndex:text.length - 1];
        if ([lastChar isEqualToString:@","] || [lastChar isEqualToString:@"，"]) {
            // 最后一个输入的字符是逗号
            
            // 去掉文本框最后一个逗号
//            self.textField.text = [text substringToIndex:text.length - 1];
            [self.textField deleteBackward];
            
            [self tipClick];
            
        } else {    // 最后一个输入的字符不是逗号
            // 排布文本框
            [self setupTextFieldFrame];
            
            self.tipButton.hidden = NO;
           
            [self.tipButton setTitle:[NSString stringWithFormat:@"添加标签:%@", text] forState:UIControlStateNormal];
        }
        
    } else {
        self.tipButton.hidden = YES;
    }
    
}

/**
 *  点击了提醒按钮
 */
- (void)tipClick{

    // 没有文字,直接返回
    if (self.textField.hasText == NO) return;
    
    if (self.tagButtons.count == 5) {
        
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showErrorWithStatus:@"最多5个标签"];
        return;
    }
    
    // 创建一个标签按钮
    LZTagButton *newTagButton = [[LZTagButton alloc] init];
    
    [newTagButton addTarget:self action:@selector(tagClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [newTagButton setTitle:self.textField.text forState:UIControlStateNormal];
    
    [self.contentView addSubview:newTagButton];
    
    // 设置位置--参照最后一个标签按钮
    // 最后一个标签按钮
    LZTagButton *lastTagButton = self.tagButtons.lastObject;
    [self setupTagButtonFrame:newTagButton referenceTagButton:lastTagButton];
    
    // 添加到数组中
    [self.tagButtons addObject:newTagButton];
    
    self.textField.text = nil;

    [self setupTextFieldFrame];
    
    // 隐藏提醒按钮
    self.tipButton.hidden = YES;
}

/**
 *  点击了标签按钮
 */
- (void)tagClick:(LZTagButton *)clickedTagButton
{
    // 即将被删除的标签按钮的索引
    NSUInteger index = [self.tagButtons indexOfObject:clickedTagButton];
    // 删除按钮
    [clickedTagButton removeFromSuperview];
    [self.tagButtons removeObject:clickedTagButton];
    
    // 处理后面的标签按钮
    NSUInteger count = self.tagButtons.count;
    for (NSUInteger i = index; i < count; i++) {
        LZTagButton *tagButton = self.tagButtons[i];
        // 如果i不为0，就参照上一个标签按钮
        LZTagButton *referenceTagButton = (i == 0) ? nil : self.tagButtons[i - 1];
        [self setupTagButtonFrame:tagButton referenceTagButton:referenceTagButton];
    }
    
    // 排布文本框
    [self setupTextFieldFrame];
}

- (void)cancel {
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)done {
    // 1.传递标签数据回到上一个界面
//    NSMutableArray *tags = [NSMutableArray array];
//    for (LZTagButton *tagButton in self.tagButtons) {
//        [tags addObject:tagButton.currentTitle];
//    }
    // 将self.tagButtons中存放的所有对象的currentTitle属性值取出来,放到一个新的数组中,并返回
    NSArray *tags = [self.tagButtons valueForKeyPath:@"currentTitle"];
    
    if (_getTagsBlock) {
        _getTagsBlock(tags);
    }
    
    // 2.关闭当前控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 设置控件的frame 
/**
 *  设置标签按钮的frame
 *
 *  @param tagButton          需要设置frame发标签按钮
 *  @param referenceTagButton 计算tagButton的frame时参照的标签按钮
 */
- (void)setupTagButtonFrame:(LZTagButton *)tagButton referenceTagButton:(LZTagButton *)referenceTagButton
{
    // 没有参照按钮(tagButton是第一个标签按钮)
    if (referenceTagButton == nil) {
        tagButton.x = 0;
        tagButton.y = 0;
        return;
    }
    
    // tagButton不是第一个标签按钮
    // 左边的总宽度
    CGFloat leftWidth = CGRectGetMaxX(referenceTagButton.frame) + LZCommonSmallMargin;
    // 右边剩下的宽度
    CGFloat rightWidth = self.contentView.width - leftWidth;
    if (rightWidth >= tagButton.width) { // 跟上一个按钮处在同一行
        tagButton.x = leftWidth;
        tagButton.y = referenceTagButton.y;
    } else {    // 下一行
        tagButton.x = 0;
        tagButton.y = CGRectGetMaxY(referenceTagButton.frame) + LZCommonSmallMargin;
    }
}

- (void)setupTextFieldFrame
{
    CGFloat textW = [self.textField.text sizeWithAttributes:@{NSFontAttributeName : self.textField.font}].width;
    textW = MAX(100, textW);
    // 排布文本框
    // 左边的总宽度
    LZTagButton *lastTagButton = self.tagButtons.lastObject;
    
    if (lastTagButton == nil) {
        
        self.textField.x = 0;
        self.textField.y = 0;
        
    } else {
        
        CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + LZCommonSmallMargin;
        // 右边剩下的宽度
        CGFloat rightWidth = self.contentView.width - leftWidth;
        if (rightWidth >= textW) {    // 跟新添加的标签按钮处在同一行
            self.textField.x = leftWidth;
            self.textField.y = lastTagButton.y;
        } else {    // 换行
            self.textField.x = 0;
            self.textField.y = CGRectGetMaxY(lastTagButton.frame) + LZCommonSmallMargin;
        }
        
    }

    // 排布提醒按钮
    // 创建一个提醒按钮
    self.tipButton.y = CGRectGetMaxY(self.textField.frame) + LZCommonSmallMargin;
}

#pragma mark - <UITextFieldDelegate>
/**
 *  点击右下角return按钮就会调用这个方法
 */
- (BOOL)textFieldShouldReturn:(LZTagTextField *)textField
{
    [self tipClick];
    return YES;
}


@end
